package com.kinon.ceshiaccount.service;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by lhqq on 2017-12-01.
 */

public class AdImageService extends Service {
    private  boolean isNewImage=true;
    private ResponseBody body;
    private String url="http://e.hiphotos.baidu.com/zhidao/pic/item/d000baa1cd11728b43937b8fc8fcc3cec2fd2ce4.jpg";


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

//    public static void verifyStoragePermissions(Activity activity) {
//        // Check if we have write permission
//        int permission = ActivityCompat.checkSelfPermission(activity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//            // We don't have permission so prompt the user
//            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
//                    REQUEST_EXTERNAL_STORAGE);
//        }
//    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        getImage();
        return super.onStartCommand(intent, flags, startId);
    }

    private void getImage(){
        Call<ResponseBody> call= HttpManage.getRequestApi().downloadImg(url);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
              body=response.body();
                myHandler.post(adRunnable);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
    private Handler myHandler=new Handler();
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("lh", "serviceonDestroy== " );
        myHandler.removeCallbacks(adRunnable);

    }
    private Runnable adRunnable=new Runnable() {
        @Override
        public void run() {
            Log.e("lh", "adRunnable== " );
            downLoadAdImage();
        }
    };
   String newpath= Environment.getExternalStorageDirectory().getPath();
    private void downLoadAdImage(){
        Log.e("lh", "== "+SunmiImgPath.pathwelcom );
        Log.e("lh", "newpath== "+newpath );
        try {
            if(!isNewImage || body==null){
                return;
            }
            Log.e("lh", "0== " );
            InputStream is=body.byteStream();
            File fileDr=new File(newpath);
            Log.e("lh", "0---1== " );
            if(!fileDr.exists()){
                Log.e("lh", "0---2== " );
                fileDr.mkdir();
                Log.e("lh", "0---3== " );
            }
            Log.e("lh", "1== " );
            File file=new File(newpath,"caizhengting.png");
            Log.e("lh", "2== " );
            if(file.exists()){
                file.delete();
                file=new File(newpath,"caizhengting.png");
//                file=new File(SunmiImgPath.sysPath,
//                        "caizhengting.png");
            }
            Log.e("lh", "3== " );
            FileOutputStream fos=new FileOutputStream(file);
            Log.e("lh", "4== " );
            BufferedInputStream bis=new BufferedInputStream(is);
            Log.e("lh", "5== " );
            byte [] buffer=new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
            fos.flush();
            fos.close();
            is.close();
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
